//
//  CLReadMarkView.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/7/18.
//

#import "CLReadMarkView.h"
#import "CLBook.h"
#import "CLReadModel.h"
@implementation CLReadMarkView

- (void)setReadModel:(CLReadModel *)readModel {
    _readModel = readModel;
    [self.tableView reloadData];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubviews];
    }
    return self;
}

- (void)addSubviews {
    self.tableView = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self addSubview:self.tableView];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.tableView.frame = self.bounds;
}

// MARK: UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.readModel) { return self.readModel.markModels.count; }
    return 0;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CLReadMarkCell *cell = [CLReadMarkCell cell:tableView];
    cell.markModel = self.readModel.markModels[indexPath.row];
    // 日夜间
    if ([CLUserDefaults boolForKey:CL_READ_KEY_MODE_DAY_NIGHT]) {
        cell.spaceLine.backgroundColor = [CL_COLOR_230_230_230 colorWithAlphaComponent:0.1];
    }else{ cell.spaceLine.backgroundColor = CL_COLOR_230_230_230; }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CL_SIZE(CL_SPACE_100);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(markViewClickMarkWithMarkView:markModel:)]) {
        [self.delegate markViewClickMark:self markModel:self.readModel.markModels[indexPath.row]];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.readModel.markModels.count == 0) {
        [tableView reloadData];
    } else {
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

@end
